import React, { useEffect, useRef, useState } from "react";
import '../../appcommon.css';
import styles from './checkin.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import icon_day_did_checkin from '@/assets/icon_day_did_checkin.png'
import icon_checkin_today from '@/assets/icon_checkin_today.png'

import NavigateBar from "@/components/NavigateBar";
import { getCoinInfo, isUnvalidUserInfo } from "@/utils/storage";
import { LangThai } from '@/utils/langThai';
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import CheckInDialog from "@/components/CheckInDialog/CheckInDialog";
import { checkin, getCheckinDetail } from "@/store/actions/checkin";
import { toFinanceString } from "@/utils/utils";

/**
 * 首充返利页
 */
export default function CheckIn() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //显示check in弹框
    const [checkInMaskVisible, setCheckInMaskVisible] = useState(false);

    // 当前月
    const [curMonth, setCurMonth] = useState("");

    // 星期头
    const [weekList, setWeekList] = useState(['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']);

    // 日期状态
    const [dayStateList, setDayStateList] = useState([]);

    // 签到收益
    const [totalIncome, setTotalIncome] = useState("*");
    const [dayIncome, setDayIncome] = useState("*");
    const [todayDidChecked, setTodayDidChecked] = useState(false);

    // 当天div
    const curDayDivRef = useRef(null);
    const successDivRef = useRef(null);
    const [successPosition, setSuccessPosition] = useState({ top: 0, left: 0, visibility: "hidden" });
    const [successFadeOut, setSuccessFadeOut] = useState(false);

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    let timer1 = null;
    let timer2 = null;

    //router

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 判断是否需要重登录
        if (isUnvalidUserInfo()) {
            history.replace('/login')
            return
        }

        // 读取缓存
        // const coinInfo = getCoinInfo();
        // let gCoinInfo = { ...coinInfo };
        // setCurCoinInfo(gCoinInfo);

        // 获取签到详情
        doGetCheckinDetail();

        //打点
        doHitEvent("CHECK_IN_START")

        return () => {
            //打点
            doHitEvent("CHECK_IN_END")
        }
    }, [])

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const initDateDisplay = (checkinDetail) => {
        const dayStateList = [];

        const curMonthInfo = getCurrentMonthInfo();

        // 需要显示上个月的天数 // 0 日 1 一 2二 3三
        const firstDayWeek = curMonthInfo.firstDayWeek;
        if (firstDayWeek > 0) {
            const perMonthDays = getPreviousMonthLastDay();
            for (let i = 1; i < firstDayWeek; i++) {
                let dayState = {};
                // dayState.day = (perMonthDays - firstDayWeek + i + 1);
                dayState.day = (perMonthDays - firstDayWeek + i + 1);
                dayState.isCurrentMonth = false;
                dayState.isCurrentDay = false;
                dayState.isCheckIn = false;
                dayState.week = i;
                dayStateList.push(dayState);
            }
        }

        // 当月
        const year = curMonthInfo.year;
        const month = curMonthInfo.month;
        const days = curMonthInfo.days;
        const curDay = parseInt(curMonthInfo.curDay);
        for (let i = 1; i <= days; i++) {
            let day = (i < 10) ? ("0" + i) : (i + "");
            const dateString = year + "-" + month + "-" + day;
            let week = getWeekInfo(dateString);


            let isCheckIn = false;
            let signinDays = checkinDetail.signinDays || [];
            for (let k = 0; k < signinDays.length; k++) {
                let checkDay = signinDays[k];
                if (checkDay === dateString) {
                    isCheckIn = true
                    break
                }
            }

            // 当天是否已签到
            if (i === curDay) {
                setTodayDidChecked(isCheckIn);
            }

            let dayState = {};
            dayState.day = i;
            dayState.isCurrentMonth = true;
            dayState.isCheckIn = isCheckIn;
            dayState.isCurrentDay = (i === curDay);
            dayState.week = week;
            dayStateList.push(dayState);
        }

        const endNeedAddCount = 35 - dayStateList.length;
        if (endNeedAddCount > 0) {
            // 最后一天的星期数 0-6
            let lastDayState = dayStateList[dayStateList.length - 1];
            const lastDayWeek = lastDayState.week;

            for (let i = 1; i <= endNeedAddCount; i++) {
                let dayState = {};
                dayState.day = i;
                dayState.isCurrentMonth = false;
                dayState.isCurrentDay = false;
                dayState.isCheckIn = false;
                dayState.week = lastDayWeek + i;
                dayStateList.push(dayState);
            }
        }

        // 更新
        const monthDes = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        let monthInt = parseInt(month) - 1;
        setCurMonth(monthDes[monthInt]);
        setDayStateList(dayStateList);
    }

    const getCurrentMonthInfo = () => {
        const nowDate = new Date();
        const y = nowDate.getFullYear();
        let m = nowDate.getMonth() + 1;
        let mF = m < 10 ? "0" + m : m;
        let d = nowDate.getDate();
        let firstDay = "01";

        let dateString = y + "-" + mF + "-" + firstDay;
        const date2 = new Date(dateString);
        // 0-6，0 表示星期日, 6表示星期六
        let week = date2.getDay();
        if (week === 0) {
            week = 7;
        }

        let info = {}
        info.firstDayWeek = week;
        info.days = new Date(y, m, 0).getDate();
        info.year = y + "";
        info.month = mF + "";
        info.curDay = d + "";
        return info;
    }

    const getWeekInfo = (dateString) => {
        const date = new Date(dateString);
        let week = date.getDay();
        if (week === 0) {
            week = 7;
        }
        return week;
    }

    const getPreviousMonthLastDay = () => {
        const nowDate = new Date();
        const y = nowDate.getFullYear();
        let m = nowDate.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        let d = "01";

        let dateString = y + "-" + m + "-" + d;
        const date2 = new Date(dateString);
        date2.setDate(date2.getDate() - 1)

        // 0-6，0 表示星期日, 6表示星期六
        const days = date2.getDate();
        console.log("pre month last day: " + days);
        return days;
    }

    const doGetCheckinDetail = async () => {
        console.log("doGetCheckinDetail: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getCheckinDetail(onDoGetCheckinDetailCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const doCheckin = async () => {
        console.log("doCheckin: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = checkin(onDoCheckinCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const onDoGetCheckinDetailCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('doGetCheckinDetail 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            let income = toFinanceString(data.totalIncome);
            setTotalIncome(income);
            let dayIncome = toFinanceString(data.dayIncome);
            setDayIncome(dayIncome);

            initDateDisplay(data || {});

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    const onDoCheckinCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('doCheckin 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            doGetCheckinDetail();

            // 展示toast
            if (successDivRef.current) {
                const successRect = successDivRef.current.getBoundingClientRect();
                // console.log('Success Div位置:', successRect);
                // {
                //     "x": 176,
                //     "y": 427.5,
                //     "width": 60,
                //     "height": 24,
                //     "top": 427.5,
                //     "right": 236,
                //     "bottom": 451.5,
                //     "left": 176
                // }

                let sLeft = successRect.left;
                let sTop = successRect.top;
                let sHeight = successRect.height;
                let sWidth = successRect.width;

                if (curDayDivRef.current) {
                    const dayRect = curDayDivRef.current.getBoundingClientRect();
                    // console.log('Current Day Div位置:', dayRect);
                    // {
                    //     "x": 70.2890625,
                    //     "y": 285.5,
                    //     "width": 54.2890625,
                    //     "height": 42,
                    //     "top": 285.5,
                    //     "right": 124.578125,
                    //     "bottom": 327.5,
                    //     "left": 70.2890625
                    // }

                    let dLeft = dayRect.left;
                    let dTop = dayRect.top;
                    let dWidth = dayRect.width;

                    sTop = dTop - sHeight + 2;

                    let dCenter = dLeft + dWidth / 2;
                    sLeft = dCenter - sWidth / 2;

                    setSuccessPosition({ top: sTop, left: sLeft, visibility: "visible", opacity: 0 });

                    // 2秒后触发淡出效果
                    setTimeout(() => {
                        setSuccessFadeOut(true);
                    }, 2000);
                }
            }

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    const onHandleCheckin = () => {
        if(timer1!=null){
            clearTimeout(timer1);
        }
        if(timer2!=null){
            clearTimeout(timer2);
        }

        if (todayDidChecked) {
            // Toast.show(curLang.checkIn7);

            // 处理流程业务
            // doGetCheckinDetail();

            // // 展示toast
            if (successDivRef.current) {
                const successRect = successDivRef.current.getBoundingClientRect();
                // console.log('Success Div位置:', successRect);
                // {
                //     "x": 176,
                //     "y": 427.5,
                //     "width": 60,
                //     "height": 24,
                //     "top": 427.5,
                //     "right": 236,
                //     "bottom": 451.5,
                //     "left": 176
                // }

                let sLeft = successRect.left;
                let sTop = successRect.top;
                let sHeight = successRect.height;
                let sWidth = successRect.width;

                if (curDayDivRef.current) {
                    const dayRect = curDayDivRef.current.getBoundingClientRect();
                    // console.log('Current Day Div位置:', dayRect);
                    // {
                    //     "x": 70.2890625,
                    //     "y": 285.5,
                    //     "width": 54.2890625,
                    //     "height": 42,
                    //     "top": 285.5,
                    //     "right": 124.578125,
                    //     "bottom": 327.5,
                    //     "left": 70.2890625
                    // }

                    let dLeft = dayRect.left;
                    let dTop = dayRect.top;
                    let dWidth = dayRect.width;

                    sTop = dTop - sHeight + 2;

                    let dCenter = dLeft + dWidth / 2;
                    sLeft = dCenter - sWidth / 2;

                    setSuccessPosition({ top: sTop, left: sLeft, visibility: "visible", opacity: 1 });

                    // 2秒后触发淡出效果
                    timer1 = setTimeout(() => {
                        setSuccessFadeOut(true);
                    }, 500);

                    timer2 = setTimeout(() => {
                        setSuccessFadeOut(false);
                        setSuccessPosition({ top: sTop, left: sLeft, visibility: "hidden", opacity: 1 });
                    }, 2000);
                }
            }

        } else {
            doCheckin();
        }
    }

    return (
        <div className={styles.checkInRoot}>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.checkIn4}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull pageContentPaddingHorizontal16px">

                {/* 日期状态 模块 */}
                <div className={styles.checkInCalendarContent}>
                    <div className={styles.checkInCurrentMonth}>{curMonth}</div>

                    {weekList.length && weekList.length > 0 && <div className={styles.checkInCalendarTable}>
                        {weekList.map((value, index) => {
                            return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                <div className={styles.checkInCalendarTableDay}>{value}</div>
                            </div>
                        })}
                    </div>}

                    {dayStateList.length && dayStateList.length > 0 && <div className={styles.checkInCalendarTable}>
                        {dayStateList.map((value, index) => {
                            if (value.isCurrentMonth) {
                                if (value.isCheckIn && value.isCurrentDay) {
                                    return <div className={styles.checkInCalendarTableDayContent} key={index} ref={curDayDivRef}>
                                        <div className={`${styles.checkInCalendarTableDay} ${styles.checkInCalendarDayModeCurDay}`}></div>
                                        <img className={styles.checkInCalendarDayModeTodayCheckedIcon} src={icon_checkin_today} alt="" />
                                    </div>
                                } else if (value.isCheckIn && (!value.isCurrentDay)) {
                                    return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                        <div className={`${styles.checkInCalendarTableDay} ${styles.checkInCalendarDayModeChecked}`}>{value.day}</div>
                                        <img className={styles.checkInCalendarDayModeCheckedIcon} src={icon_day_did_checkin} alt="" />
                                    </div>
                                } else if ((!value.isCheckIn) && value.isCurrentDay) {
                                    return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                        <div className={`${styles.checkInCalendarTableDay} ${styles.checkInCalendarDayModeCurDay}`}>{value.day}</div>
                                    </div>
                                } else if ((!value.isCheckIn) && (!value.isCurrentDay)) {
                                    return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                        <div className={`${styles.checkInCalendarTableDay} ${styles.checkInCalendarDayModeInMonth}`}>{value.day}</div>
                                    </div>
                                } else {
                                    return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                        <div className={`${styles.checkInCalendarTableDay} ${styles.checkInCalendarDayModeInMonth}`}>{value.day}</div>
                                    </div>
                                }
                            } else {
                                return <div className={styles.checkInCalendarTableDayContent} key={index}>
                                    <div className={styles.checkInCalendarTableDay}>{value.day}</div>
                                </div>
                            }
                        })}
                    </div>}
                </div>

                {/* amount 模块 */}
                <div className={styles.checkInSectionContent}>
                    <div className={styles.checkInAmountContent}>
                        <div className={styles.checkInAmountTitle}>{curLang.checkIn1}</div>
                        <div className={styles.checkInAmountDetail}>{totalIncome} {curLang.checkIn21}</div>
                    </div>

                    {todayDidChecked && <div className={styles.checkInAmountTransferDisable} onClick={onHandleCheckin}>{curLang.checkIn2}{dayIncome} {curLang.checkIn21}</div>}
                    {!todayDidChecked && <div className={styles.checkInAmountTransfer} onClick={onHandleCheckin}>{curLang.checkIn2}{dayIncome} {curLang.checkIn21}</div>}

                    <div className={styles.checkInTipDetail}>{curLang.checkIn3}</div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>

            {/* 签到提示 */}
            <CheckInDialog visible={checkInMaskVisible} onConfirm={() => { setCheckInMaskVisible(false) }}></CheckInDialog>

            <div className={`${styles.checkInSuccessToast} ${successFadeOut ? styles.checkInToastDismissFadeOut : ''}`} style={{ top: successPosition.top, left: successPosition.left, opacity: successPosition.opacity, visibility: successPosition.visibility, opacity: successPosition.opacity }} ref={successDivRef}>+{dayIncome}</div>

        </div >
    )
}